package com.demo.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.core.exception.ParameterException;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class PageMessage<T> {
    public long pageNum;//总共页数
    public long pageSize;//单页容量
    public long total;//数据总数
    public long current;//当前页数
//    public List<T> data;

//    构造方法，封装分页的信息（所有数据）
    public PageMessage(long pageNum,long pageSize,long total,long current){
        this.pageNum=pageNum;
        this.pageSize=pageSize;
        this.total=total;
        this.current=current;
    }

//    构造方法，封装分页的信息（当前页和页的容量）
    public PageMessage(long current,long pageSize){
        this.pageSize=pageSize;
        this.current=current;
    }

//    对某个数据列表进行分页
    public Page<T> pageForList(List<T> list) throws ParameterException {
        if(list.size()==0){
            throw new ParameterException("待分页的列表为空");
        }
        else {
            Page<T> page = new Page<>(current, pageSize);
            long count = list.size();
            List<T> pageList = new ArrayList<>();
            //计算当前页第一条数据的下标
            long currId = current > 1 ? (current - 1) * pageSize : 0;
            for (long i = 0; i < pageSize && i < count - currId; i++) {
                pageList.add(list.get((int)(currId + i)));
            }
            page.setSize(pageSize);
            page.setCurrent(current);
            page.setTotal(count);
            //计算分页总页数
            page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
            page.setRecords(pageList);
            return page;
        }
    }

}
